<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>n8n工作流监控系统</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', '微软雅黑', 'PingFang SC', 'Hiragino Sans GB', 'Heiti SC', 'WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Source Han Sans CN', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
        
        button, input, select, textarea {
            font-family: inherit;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header .update-time {
            font-size: 0.9em;
            opacity: 0.9;
        }
        
        .refresh-btn {
            background: white;
            color: #667eea;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            margin-top: 15px;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            font-family: inherit;
        }
        
        .refresh-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            cursor: pointer;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
        }
        
        .stat-card.clickable {
            cursor: pointer;
        }
        
        .stat-card.clickable:hover {
            background: #f8f9fa;
        }
        
        .stat-card .label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 10px;
        }
        
        .stat-card .value {
            font-size: 2.5em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
        
        .stat-card .subtext {
            font-size: 0.85em;
            color: #999;
        }
        
        .stat-card.success .value {
            color: #10b981;
        }
        
        .stat-card.warning .value {
            color: #f59e0b;
        }
        
        .stat-card.danger .value {
            color: #ef4444;
        }
        
        .chart-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .chart-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
        }
        
        .chart-container {
            position: relative;
            height: 400px;
            margin-bottom: 20px;
        }
        
        .issues-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .issues-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
        }
        
        .issue-item {
            border-left: 4px solid #ef4444;
            background: #fef2f2;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 5px;
        }
        
        .issue-item .issue-type {
            font-weight: bold;
            color: #ef4444;
            margin-bottom: 5px;
        }
        
        .issue-item .issue-content {
            color: #666;
            margin-bottom: 5px;
            line-height: 1.6;
        }
        
        .issue-item .issue-meta {
            font-size: 0.85em;
            color: #999;
        }
        
        .no-issues {
            text-align: center;
            color: #10b981;
            font-size: 1.2em;
            padding: 30px;
        }
        
        .table-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-top: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            overflow-x: auto;
        }
        
        .table-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        table th {
            background: #667eea;
            color: white;
            padding: 12px;
            text-align: left;
            font-weight: 600;
        }
        
        table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
        }
        
        table tr:hover {
            background: #f9fafb;
        }
        
        .clickable-row:hover {
            background: #e3f2fd !important;
            cursor: pointer;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.85em;
            font-weight: 600;
        }
        
        .badge.success {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge.danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .loading {
            text-align: center;
            color: white;
            font-size: 1.5em;
            padding: 50px;
        }
        
        .error-message {
            background: #fee2e2;
            color: #991b1b;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin: 20px 0;
        }
        
        /* 回流率模块样式 */
        .reply-rate-module {
            grid-column: span 2;
        }
        
        .reply-rate-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-top: 15px;
        }
        
        .reply-rate-item {
            text-align: center;
            padding: 15px;
            border-radius: 10px;
            background: #f8f9fa;
        }
        
        .reply-rate-item.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .reply-rate-item.active {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .reply-rate-item.passive {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
        }
        
        .rate-label {
            font-size: 0.9em;
            margin-bottom: 8px;
            opacity: 0.9;
        }
        
        .rate-value {
            font-size: 1.8em;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .rate-detail {
            font-size: 0.8em;
            opacity: 0.8;
        }
        
        /* 候选人统计模块样式 */
        .candidate-count-module {
            grid-column: span 2;
        }
        
        .candidate-count-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-top: 15px;
        }
        
        .candidate-count-item {
            text-align: center;
            padding: 15px;
            border-radius: 10px;
            background: #f8f9fa;
        }
        
        .candidate-count-item.total {
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: white;
        }
        
        .candidate-count-item.active {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .candidate-count-item.passive {
            background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
            color: white;
        }
        
        .count-label {
            font-size: 0.9em;
            margin-bottom: 8px;
            opacity: 0.9;
        }
        
        .count-value {
            font-size: 1.8em;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 n8n工作流监控系统</h1>
            <p class="update-time">更新时间: <span id="updateTime">加载中...</span></p>
            <button class="refresh-btn" onclick="window.location.reload()">🔄 刷新数据</button>
            <div id="dbInfo"></div>
        </div>
        
        <div id="loadingMessage" class="loading">
            正在加载数据...
        </div>
        
        <div id="errorMessage" class="error-message" style="display: none;">
            ❌ 无法加载数据。请确保已运行 monitor.py 生成报告文件。
        </div>
        
        <div id="content" style="display: none;">
            <!-- 评估操作区域 -->
            <div style="background: white; border-radius: 15px; padding: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); margin-bottom: 30px;">
                <h2 style="color: #333; margin-bottom: 20px; font-size: 1.5em; text-align: center;">🔍 信息评估</h2>
                <div style="display: flex; justify-content: center; gap: 20px; flex-wrap: wrap;">
                    <button class="evaluate-btn" onclick="startAIMessageEvaluation()" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 20px 50px; border-radius: 50px; font-size: 1.2em; font-weight: bold; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
                        🤖 AI信息统计
                    </button>
                    <button class="evaluate-btn" onclick="startUserMessageEvaluation()" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border: none; padding: 20px 50px; border-radius: 50px; font-size: 1.2em; font-weight: bold; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
                        👤 用户信息评估
                    </button>
                    <button class="evaluate-btn" onclick="startReplyReasonableEvaluation()" style="background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%); color: white; border: none; padding: 20px 50px; border-radius: 50px; font-size: 1.2em; font-weight: bold; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
                        💬 回复合理评估
                    </button>
                </div>
                <p style="text-align: center; color: #666; margin-top: 15px; font-size: 0.9em;">
                    点击按钮开始评估候选人和AI的消息内容
                </p>
            </div>
            
            <!-- 核心指标卡片 -->
            <div class="stats-grid">
                <div class="stat-card reply-rate-module">
                    <div class="label">📈 回流率统计</div>
                    <div class="reply-rate-grid">
                        <div class="reply-rate-item total">
                            <div class="rate-label">总回流率</div>
                            <div class="rate-value" id="totalReplyRate">-</div>
                            <div class="rate-detail" id="totalReplyDetail">-</div>
                        </div>
                        <div class="reply-rate-item active">
                            <div class="rate-label">主动回流率</div>
                            <div class="rate-value" id="activeReplyRate">-</div>
                            <div class="rate-detail" id="activeReplyDetail">-</div>
                        </div>
                        <div class="reply-rate-item passive">
                            <div class="rate-label">被动回流率</div>
                            <div class="rate-value" id="passiveReplyRate">-</div>
                            <div class="rate-detail" id="passiveReplyDetail">-</div>
                        </div>
                    </div>
                </div>
                
                <div class="stat-card candidate-count-module">
                    <div class="label">👥 候选人统计</div>
                    <div class="candidate-count-grid">
                        <div class="candidate-count-item total">
                            <div class="count-label">总候选人</div>
                            <div class="count-value" id="totalCandidates">-</div>
                        </div>
                        <div class="candidate-count-item active">
                            <div class="count-label">主动候选人</div>
                            <div class="count-value" id="activeCount">-</div>
                        </div>
                        <div class="candidate-count-item passive">
                            <div class="count-label">被动候选人</div>
                            <div class="count-value" id="passiveCount">-</div>
                        </div>
                    </div>
                </div>
                
                <div class="stat-card warning clickable" onclick="navigateToSalaryDetail()">
                    <div class="label">💰 薪资信息提及</div>
                    <div class="value" id="salaryCount">-</div>
                    <div class="subtext">占AI消息: <span id="salaryRate">-</span>%</div>
                </div>
                
                <div class="stat-card danger clickable" onclick="navigateToDetail('sensitive')">
                    <div class="label">⚠️ 敏感词检测</div>
                    <div class="value" id="sensitiveCount">-</div>
                    <div class="subtext">需要关注</div>
                </div>
                
                <div class="stat-card success clickable" onclick="navigateToDetail('reply_reasonable')">
                    <div class="label">🤖 AI回复合理评估</div>
                    <div class="value" id="replyReasonableCount">-</div>
                    <div class="subtext">总消息对: <span id="replyReasonableTotal">-</span></div>
                </div>
                
                <div class="stat-card warning clickable" onclick="navigateToPhotoOnlyDetail()">
                    <div class="label">📸 索要照片信息</div>
                    <div class="value" id="photoRequestCount">-</div>
                    <div class="subtext">占AI消息: <span id="photoRequestRate">-</span>%</div>
                </div>
                
                <div class="stat-card success clickable" onclick="navigateToDetail('greeting')">
                    <div class="label">👋 打招呼信息</div>
                    <div class="value" id="greetingCount">-</div>
                    <div class="subtext">占AI消息: <span id="greetingRate">-</span>%</div>
                </div>
                
                <div class="stat-card">
                    <div class="label">💬 AI消息总数</div>
                    <div class="value" id="aiMessageCount">-</div>
                    <div class="subtext">近7天数据</div>
                </div>
            </div>
            
            <!-- 每日消息趋势图 -->
            <div class="chart-section">
                <h2>📈 每日消息趋势（近30天）</h2>
                <div class="chart-container">
                    <canvas id="dailyTrendChart"></canvas>
                </div>
            </div>
            
            <!-- 增强统计信息 -->
            <div class="chart-section">
                <h2>📊 数据质量与趋势分析</h2>
                <div class="stats-grid" id="enhancedStatsGrid">
                    <!-- 动态填充 -->
                </div>
            </div>
            
            <!-- 回流率详情图 -->
            <div class="chart-section">
                <h2>🎯 回流情况分析</h2>
                <div class="chart-container">
                    <canvas id="replyRateChart"></canvas>
                </div>
            </div>
            
            <!-- 问题列表 -->
            <div class="issues-section">
                <h2>⚠️ 敏感词检测详情</h2>
                <div id="issuesList">
                    <!-- 动态填充 -->
                </div>
            </div>
            
            <!-- 候选人详情表 -->
            <div class="table-section">
                <h2>👥 候选人回流详情</h2>
                <table>
                    <thead>
                        <tr>
                            <th>姓名</th>
                            <th>Boss UID</th>
                            <th>状态</th>
                            <th>消息数</th>
                            <th>是否回流</th>
                        </tr>
                    </thead>
                    <tbody id="candidateTable">
                        <!-- 动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <script>
        // 加载监控数据
        async function loadMonitorData() {
            try {
                const response = await fetch('static/monitor_report.json');
                if (!response.ok) throw new Error('无法加载报告文件');
                
                const data = await response.json();
                displayData(data);
                
                document.getElementById('loadingMessage').style.display = 'none';
                document.getElementById('content').style.display = 'block';
                
            } catch (error) {
                console.error('加载数据失败:', error);
                document.getElementById('loadingMessage').style.display = 'none';
                document.getElementById('errorMessage').style.display = 'block';
            }
        }
        
        // 加载MySQL实时统计数据
        async function loadMySQLStatistics() {
            try {
                console.log('========== 开始加载MySQL实时统计 ==========');
                const response = await fetch('/api/mysql-statistics');
                
                if (!response.ok) {
                    console.error('无法加载MySQL统计:', response.status);
                    return;
                }
                
                const data = await response.json();
                console.log('MySQL统计数据:', data);
                
                if (data.success && data.has_data) {
                    // 显示数据库连接信息
                    displayDatabaseInfo(data.database_info);
                    console.log('MySQL实时统计加载成功');
                    console.log(`  候选人总数: ${data.total_candidates}`);
                    console.log(`  最近30天候选人: ${data.recent_candidates}`);
                    console.log(`  AI消息数: ${data.ai_messages}`);
                    console.log(`  用户消息数: ${data.user_messages}`);
                } else {
                    console.log('暂无MySQL统计数据');
                }
                
            } catch (error) {
                console.error('加载MySQL统计失败:', error);
            }
        }
        
        // 显示数据库信息
        function displayDatabaseInfo(dbInfo) {
            const dbInfoDiv = document.getElementById('dbInfo');
            if (dbInfoDiv && dbInfo) {
                dbInfoDiv.innerHTML = `
                    <div style="background: rgba(255,255,255,0.2); padding: 15px; border-radius: 10px; margin-top: 20px;">
                        <strong>📊 数据库连接信息</strong><br>
                        主机: ${dbInfo.host || 'unknown'}<br>
                        数据库: ${dbInfo.database || 'unknown'}<br>
                        状态: <span style="color: #4ade80;">${dbInfo.connected ? '✅ 已连接' : '❌ 未连接'}</span><br>
                        <span style="font-size: 0.9em; opacity: 0.9;">数据实时更新中...</span>
                    </div>
                `;
                console.log('数据库信息已更新:', dbInfo);
            }
        }
        
        // 加载评估统计数据
        async function loadEvaluationStatistics() {
            try {
                console.log('开始加载评估统计数据...');
                const response = await fetch('/api/evaluation-statistics');
                
                if (!response.ok) {
                    console.warn('无法加载评估统计:', response.status);
                    return;
                }
                
                const data = await response.json();
                console.log('评估统计数据:', data);
                
                if (data.has_data) {
                    updateEvaluationCards(data);
                } else {
                    console.log('暂无评估统计数据');
                }
                
            } catch (error) {
                console.warn('加载评估统计失败:', error);
            }
        }
        
        // 更新评估统计卡片
        function updateEvaluationCards(data) {
            console.log('更新评估统计卡片:', data);
            
            // 更新薪资相关消息数
            if (data.salary_messages_count !== undefined) {
                document.getElementById('salaryCount').textContent = data.salary_messages_count;
                // 计算薪资消息占比
                const totalAIMessages = data.total_ai_messages || 0;
                const salaryRate = totalAIMessages > 0 ? ((data.salary_messages_count / totalAIMessages) * 100).toFixed(2) : '0.00';
                document.getElementById('salaryRate').textContent = salaryRate;
            }
            
            // 更新索要照片信息数
            if (data.photo_messages_count !== undefined) {
                document.getElementById('photoRequestCount').textContent = data.photo_messages_count;
                const totalAIMessages = data.total_ai_messages || 0;
                const photoRate = totalAIMessages > 0 ? ((data.photo_messages_count / totalAIMessages) * 100).toFixed(2) : '0.00';
                document.getElementById('photoRequestRate').textContent = photoRate;
            }
        }
        
        // 加载回复合理评估统计数据
        async function loadReplyReasonableStatistics() {
            try {
                console.log('开始加载回复合理评估统计数据...');
                const response = await fetch('/api/reply-reasonable-statistics');
                
                if (!response.ok) {
                    console.warn('无法加载回复合理评估统计:', response.status);
                    return;
                }
                
                const data = await response.json();
                console.log('回复合理评估统计数据:', data);
                
                if (data.has_data) {
                    updateReplyReasonableCard(data);
                } else {
                    console.log('暂无回复合理评估统计数据');
                }
                
            } catch (error) {
                console.warn('加载回复合理评估统计失败:', error);
            }
        }
        
        // 更新回复合理评估卡片
        function updateReplyReasonableCard(data) {
            console.log('更新回复合理评估卡片:', data);
            
            // 更新合理回复数
            if (data.reasonable_count !== undefined) {
                document.getElementById('replyReasonableCount').textContent = data.reasonable_count;
            }
            
            // 更新总消息对数
            if (data.total_pairs !== undefined) {
                document.getElementById('replyReasonableTotal').textContent = data.total_pairs;
            }
        }
        
        // 显示数据
        function displayData(data) {
            const summary = data.summary;
            
            // 更新时间
            document.getElementById('updateTime').textContent = data.generated_at;
            
            // 回流率统计
            document.getElementById('totalReplyRate').textContent = summary.total_reply_rate + '%';
            document.getElementById('totalReplyDetail').textContent = 
                `${summary.total_replied_candidates} / ${summary.total_candidates} 人回流`;
            
            document.getElementById('activeReplyRate').textContent = summary.active_reply_rate + '%';
            document.getElementById('activeReplyDetail').textContent = 
                `${summary.active_replied_candidates} / ${summary.active_candidates} 人回流`;
            
            document.getElementById('passiveReplyRate').textContent = summary.passive_reply_rate + '%';
            document.getElementById('passiveReplyDetail').textContent = 
                `${summary.passive_replied_candidates} / ${summary.passive_candidates} 人回流`;
            
            // 候选人统计
            document.getElementById('totalCandidates').textContent = summary.total_candidates;
            document.getElementById('activeCount').textContent = summary.active_candidates;
            document.getElementById('passiveCount').textContent = summary.passive_candidates;
            
            // 从AI分析数据中获取薪资信息，如果AI分析失败或数据为空则使用传统方法
            if (data.ai_salary_analysis && 
                typeof data.ai_salary_analysis.total_salary_messages === 'number' &&
                data.ai_salary_analysis.total_salary_messages > 0) {
                // AI分析数据可用且有效
                document.getElementById('salaryCount').textContent = data.ai_salary_analysis.total_salary_messages;
                document.getElementById('salaryRate').textContent = (data.ai_salary_analysis.overall_salary_rate || 0).toFixed(2);
            } else {
                // 回退到传统关键词分析方法
                const salaryStats = analyzeSalaryInfo(data.reply_rate_details.details || []);
                document.getElementById('salaryCount').textContent = salaryStats.salary_mentions;
                document.getElementById('salaryRate').textContent = salaryStats.salary_rate;
            }
            
            document.getElementById('sensitiveCount').textContent = summary.sensitive_issues;
            
            // 从真实数据中计算索要照片信息，添加容错处理
            const photoStats = analyzePhotoRequestInfo(data.reply_rate_details.details || []);
            document.getElementById('photoRequestCount').textContent = photoStats.photo_requests;
            document.getElementById('photoRequestRate').textContent = photoStats.photo_request_rate;
            
            // 从报告数据中获取打招呼信息
            const greetingCount = data.greeting_analysis ? data.greeting_analysis.greeting_count : 0;
            const greetingRate = data.greeting_analysis ? data.greeting_analysis.greeting_rate : 0;
            document.getElementById('greetingCount').textContent = greetingCount;
            document.getElementById('greetingRate').textContent = greetingRate;
            
            document.getElementById('aiMessageCount').textContent = summary.total_ai_messages;
            
            // 绘制图表
            drawDailyTrendChart(data.daily_statistics);
            drawReplyRateChart(data.reply_rate_details);
            
            // 显示增强统计信息
            displayEnhancedStats(data.enhanced_statistics);
            
            // 显示问题列表
            displayIssues(data.content_analysis.issues);
            
            // 显示候选人详情表
            displayCandidateTable(data.reply_rate_details.details || []);
        }
        
        // 绘制每日趋势图
        function drawDailyTrendChart(dailyData) {
            const ctx = document.getElementById('dailyTrendChart').getContext('2d');
            
            const dates = dailyData.map(d => d.date);
            const aiMessages = dailyData.map(d => d.ai_messages);
            const candidateMessages = dailyData.map(d => d.candidate_messages);
            const activeCandidates = dailyData.map(d => d.active_candidates);
            
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: dates,
                    datasets: [
                        {
                            label: 'AI发送消息',
                            data: aiMessages,
                            borderColor: '#667eea',
                            backgroundColor: 'rgba(102, 126, 234, 0.1)',
                            tension: 0.4
                        },
                        {
                            label: '候选人消息',
                            data: candidateMessages,
                            borderColor: '#10b981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            tension: 0.4
                        },
                        {
                            label: '活跃候选人数',
                            data: activeCandidates,
                            borderColor: '#f59e0b',
                            backgroundColor: 'rgba(245, 158, 11, 0.1)',
                            tension: 0.4,
                            yAxisID: 'y1'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    scales: {
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            title: {
                                display: true,
                                text: '消息数量'
                            }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            title: {
                                display: true,
                                text: '候选人数'
                            },
                            grid: {
                                drawOnChartArea: false,
                            }
                        }
                    }
                }
            });
        }
        
        // 绘制回流率图表
        function drawReplyRateChart(replyData) {
            const ctx = document.getElementById('replyRateChart').getContext('2d');
            
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['已回流', '未回流'],
                    datasets: [{
                        data: [
                            replyData.replied_count,
                            replyData.tracked_count - replyData.replied_count
                        ],
                        backgroundColor: [
                            '#10b981',
                            '#e5e7eb'
                        ],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed || 0;
                                    const total = replyData.tracked_count;
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }
        
        // 显示问题列表
        function displayIssues(issues) {
            const container = document.getElementById('issuesList');
            
            // 添加空值保护
            if (!issues || !Array.isArray(issues) || issues.length === 0) {
                container.innerHTML = '<div class="no-issues">✅ 暂无敏感词问题</div>';
                return;
            }
            
            container.innerHTML = issues.map(issue => `
                <div class="issue-item">
                    <div class="issue-type">🚨 ${issue.type === 'sensitive_word' ? '敏感词检测' : '其他问题'}</div>
                    <div class="issue-content">候选人: ${issue.candidate_name} | 检测到: ${issue.detected_words.join(', ')}</div>
                    <div class="issue-content">内容: ${issue.content}</div>
                    <div class="issue-meta">时间: ${issue.created_at}</div>
                </div>
            `).join('');
        }
        
        // 显示候选人详情表
        function displayCandidateTable(candidates) {
            const tbody = document.getElementById('candidateTable');
            
            // 添加空值保护
            if (!candidates || !Array.isArray(candidates) || candidates.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">暂无数据</td></tr>';
                return;
            }
            
            tbody.innerHTML = candidates.map(c => `
                <tr class="clickable-row" onclick="navigateToUserChat(${c.id})" style="cursor: pointer;">
                    <td>${c.name}</td>
                    <td>${c.boss_uid}</td>
                    <td>${c.status}</td>
                    <td>${c.total_messages}</td>
                    <td>
                        ${c.replied_back ? 
                            '<span class="badge success">✅ 已回流</span>' : 
                            '<span class="badge danger">❌ 未回流</span>'}
                    </td>
                </tr>
            `).join('');
        }
        
        // 显示增强统计信息
        function displayEnhancedStats(enhancedStats) {
            const container = document.getElementById('enhancedStatsGrid');
            
            if (!enhancedStats) {
                container.innerHTML = '<div class="no-data">暂无增强统计数据</div>';
                return;
            }
            
            const stats = [
                {
                    label: '数据质量评分',
                    value: enhancedStats.data_quality_score + '/100',
                    color: enhancedStats.data_quality_score >= 80 ? 'success' : enhancedStats.data_quality_score >= 60 ? 'warning' : 'danger'
                },
                {
                    label: '平均每日消息',
                    value: enhancedStats.avg_daily_messages,
                    color: 'normal'
                },
                {
                    label: '平均每日活跃用户',
                    value: enhancedStats.avg_daily_active_candidates,
                    color: 'normal'
                },
                {
                    label: 'AI消息占比',
                    value: enhancedStats.ai_message_ratio + '%',
                    color: 'normal'
                },
                {
                    label: '消息趋势',
                    value: getTrendText(enhancedStats.message_trend, enhancedStats.message_growth_rate),
                    color: getTrendColor(enhancedStats.message_trend)
                },
                {
                    label: '活跃用户趋势',
                    value: getTrendText(enhancedStats.active_trend, enhancedStats.active_growth_rate),
                    color: getTrendColor(enhancedStats.active_trend)
                }
            ];
            
            container.innerHTML = stats.map(stat => `
                <div class="stat-card ${stat.color}">
                    <div class="label">${stat.label}</div>
                    <div class="value">${stat.value}</div>
                </div>
            `).join('');
        }
        
        // 获取趋势文本
        function getTrendText(trend, growthRate) {
            if (trend === 'increasing') {
                return `↗ +${growthRate}%`;
            } else if (trend === 'decreasing') {
                return `↘ ${growthRate}%`;
            } else if (trend === 'stable') {
                return `→ 稳定`;
            } else {
                return '数据不足';
            }
        }
        
        // 获取趋势颜色
        function getTrendColor(trend) {
            if (trend === 'increasing') {
                return 'success';
            } else if (trend === 'decreasing') {
                return 'danger';
            } else if (trend === 'stable') {
                return 'normal';
            } else {
                return 'warning';
            }
        }
        
        // 跳转到详情页
        function navigateToDetail(type) {
            if (type === 'greeting') {
                window.location.href = 'greeting_detail.html';
            } else if (type === 'photo_request') {
                window.location.href = 'photo_detail.html';
            } else if (type === 'reply_reasonable') {
                window.location.href = 'reply_reasonable_detail.html';
            } else {
                window.location.href = `detail.html?type=${type}`;
            }
        }
        
        // 回复合理评估
        function startReplyReasonableEvaluation() {
            window.location.href = 'reply_reasonable_detail.html';
        }
        
        // 跳转到薪资详情页
        function navigateToSalaryDetail() {
            window.location.href = 'salary_detail.html';
        }
        
        // 跳转到要照片信息统计页
        function navigateToPhotoOnlyDetail() {
            console.log('[导航] 索要照片信息 -> photo_only_detail.html');
            window.location.href = 'photo_only_detail.html';
        }
        
        // 跳转到用户聊天记录页面
        function navigateToUserChat(candidateId) {
            window.location.href = `user_chat.html?candidate_id=${candidateId}`;
        }
        
        // 分析薪资信息
        function analyzeSalaryInfo(candidates) {
            // 添加空值保护
            if (!candidates || !Array.isArray(candidates)) {
                return {
                    total_ai_messages: 0,
                    salary_mentions: 0,
                    salary_rate: 0
                };
            }
            
            let totalAiMessages = 0;
            let salaryMentions = 0;
            
            // 薪资相关关键词
            const salaryKeywords = ['工资', '薪资', '薪水', '待遇', '收入', '报酬', '元', '钱', '日结', '月结', '保底', '提成'];
            
            candidates.forEach(candidate => {
                if (candidate.chat_history) {
                    candidate.chat_history.forEach(msg => {
                        if (msg.sender === '我') {
                            totalAiMessages++;
                            
                            // 检查是否包含薪资信息
                            const hasSalaryInfo = salaryKeywords.some(keyword => 
                                msg.content.includes(keyword)
                            );
                            
                            if (hasSalaryInfo) {
                                salaryMentions++;
                            }
                        }
                    });
                }
            });
            
            const salaryRate = totalAiMessages > 0 ? (salaryMentions / totalAiMessages * 100).toFixed(2) : 0;
            
            return {
                total_ai_messages: totalAiMessages,
                salary_mentions: salaryMentions,
                salary_rate: salaryRate
            };
        }

        // 分析索要照片信息
        function analyzePhotoRequestInfo(candidates) {
            // 添加空值保护
            if (!candidates || !Array.isArray(candidates)) {
                return {
                    total_ai_messages: 0,
                    photo_requests: 0,
                    photo_request_rate: 0
                };
            }
            
            let totalAiMessages = 0;
            let photoRequests = 0;
            
            // 索要照片相关关键词
            const photoKeywords = ['照片', '生活照', '看看', '评估', '上镜', '整体感觉', '发几张', '发张'];
            
            candidates.forEach(candidate => {
                if (candidate.chat_history) {
                    candidate.chat_history.forEach(msg => {
                        if (msg.sender === '我') {
                            totalAiMessages++;
                            
                            // 检查是否包含索要照片信息
                            const hasPhotoRequest = photoKeywords.some(keyword => 
                                msg.content.includes(keyword)
                            );
                            
                            if (hasPhotoRequest) {
                                photoRequests++;
                            }
                        }
                    });
                }
            });
            
            const photoRequestRate = totalAiMessages > 0 ? (photoRequests / totalAiMessages * 100).toFixed(2) : 0;
            
            return {
                total_ai_messages: totalAiMessages,
                photo_requests: photoRequests,
                photo_request_rate: photoRequestRate
            };
        }

        // AI信息统计
        function startAIMessageEvaluation() {
            // 跳转到综合统计页面（包含薪资和照片信息）
            console.log('[导航] AI信息统计 -> photo_detail.html');
            window.location.href = 'photo_detail.html';
        }
        
        // 用户信息评估
        function startUserMessageEvaluation() {
            // 跳转到用户信息评估页面
            window.location.href = 'user_sensitive_evaluation.html';
        }

        // 页面加载时执行
        window.addEventListener('DOMContentLoaded', async function() {
            await loadMonitorData();
            await loadMySQLStatistics();  // 加载MySQL实时统计
            await loadEvaluationStatistics();
            await loadReplyReasonableStatistics();
        });
    </script>
</body>
</html>

